<?php

namespace app\controller\api;

use app\model\CouponModel;
use app\model\UserCouponModel;
use support\Request;
use app\exception\BusinessException;
use hg\apidoc\annotation as Apidoc;

/**
 * @Apidoc\Title("优惠券接口")
 * @Apidoc\Group("api")
 */
class CouponController
{
    /**
     * @Apidoc\Title("获取优惠券列表")
     * @Apidoc\Method("GET")
     * @Apidoc\Url("/api/coupon/list")
     * @Apidoc\Param("page", type="int", default=1, desc="页码")
     * @Apidoc\Param("page_size", type="int", default=10, desc="每页数量")
     */
    public function list(Request $request)
    {
        $user = $request->user;
        $page = $request->get('page', 1);
        $pageSize = $request->get('page_size', 10);
        
        // 获取可领取的优惠券
        $query = CouponModel::where('status', 1)
            ->where('start_time', '<=', date('Y-m-d H:i:s'))
            ->where('end_time', '>=', date('Y-m-d H:i:s'))
            ->where(function ($query) {
                $query->where('total', 0)
                    ->orWhereRaw('used < total');
            });
            
        $coupons = $query->orderBy('id', 'desc')
            ->paginate($pageSize, ['*'], 'page', $page);
            
        // 查询用户已领取的优惠券
        $userCoupons = UserCouponModel::where('user_id', $user->id)
            ->whereIn('coupon_id', $coupons->pluck('id'))
            ->get()
            ->pluck('coupon_id')
            ->toArray();
            
        // 标记是否已领取
        foreach ($coupons as $coupon) {
            $coupon->is_received = in_array($coupon->id, $userCoupons);
            $coupon->can_receive = !$coupon->is_received && 
                (!$coupon->per_limit || UserCouponModel::where('user_id', $user->id)
                    ->where('coupon_id', $coupon->id)
                    ->count() < $coupon->per_limit);
        }
        
        return json(['code' => 0, 'msg' => 'success', 'data' => $coupons]);
    }
    
    /**
     * @Apidoc\Title("获取优惠券详情")
     * @Apidoc\Method("GET")
     * @Apidoc\Url("/api/coupon/detail/{id}")
     * @Apidoc\Param("id", type="int", require=true, desc="优惠券ID")
     */
    public function detail(Request $request, $id)
    {
        $user = $request->user;
        $coupon = CouponModel::find($id);
        
        if (!$coupon) {
            throw new BusinessException('优惠券不存在');
        }
        
        // 查询用户是否已领取
        $userCoupon = UserCouponModel::where('user_id', $user->id)
            ->where('coupon_id', $id)
            ->first();
            
        $coupon->is_received = !empty($userCoupon);
        $coupon->can_receive = !$coupon->is_received && 
            (!$coupon->per_limit || UserCouponModel::where('user_id', $user->id)
                ->where('coupon_id', $id)
                ->count() < $coupon->per_limit);
        
        return json(['code' => 0, 'msg' => 'success', 'data' => $coupon]);
    }
    
    /**
     * @Apidoc\Title("领取优惠券")
     * @Apidoc\Method("POST")
     * @Apidoc\Url("/api/coupon/receive/{id}")
     * @Apidoc\Param("id", type="int", require=true, desc="优惠券ID")
     */
    public function receive(Request $request, $id)
    {
        $user = $request->user;
        
        try {
            \DB::beginTransaction();
            
            $coupon = CouponModel::where('status', 1)
                ->where('start_time', '<=', date('Y-m-d H:i:s'))
                ->where('end_time', '>=', date('Y-m-d H:i:s'))
                ->lockForUpdate()
                ->find($id);
                
            if (!$coupon) {
                throw new BusinessException('优惠券不存在或已过期');
            }
            
            // 检查是否已领取
            if (UserCouponModel::where('user_id', $user->id)
                ->where('coupon_id', $id)
                ->exists()
            ) {
                throw new BusinessException('您已领取过该优惠券');
            }
            
            // 检查领取限制
            if ($coupon->per_limit > 0) {
                $count = UserCouponModel::where('user_id', $user->id)
                    ->where('coupon_id', $id)
                    ->count();
                    
                if ($count >= $coupon->per_limit) {
                    throw new BusinessException('超过领取限制');
                }
            }
            
            // 检查库存
            if ($coupon->total > 0 && $coupon->used >= $coupon->total) {
                throw new BusinessException('优惠券已领完');
            }
            
            // 创建用户优惠券
            $userCoupon = new UserCouponModel();
            $userCoupon->user_id = $user->id;
            $userCoupon->coupon_id = $id;
            $userCoupon->status = 0;
            $userCoupon->save();
            
            // 更新优惠券已领取数量
            $coupon->increment('used');
            
            \DB::commit();
            
            return json(['code' => 0, 'msg' => '领取成功', 'data' => $userCoupon]);
        } catch (\Exception $e) {
            \DB::rollBack();
            throw new BusinessException($e->getMessage());
        }
    }
    
    /**
     * @Apidoc\Title("我的优惠券")
     * @Apidoc\Method("GET")
     * @Apidoc\Url("/api/coupon/my")
     * @Apidoc\Param("page", type="int", default=1, desc="页码")
     * @Apidoc\Param("page_size", type="int", default=10, desc="每页数量")
     * @Apidoc\Param("status", type="int", desc="状态：0未使用，1已使用，2已过期")
     */
    public function my(Request $request)
    {
        $user = $request->user;
        $status = $request->get('status');
        $page = $request->get('page', 1);
        $pageSize = $request->get('page_size', 10);
        
        $query = UserCouponModel::with(['coupon'])
            ->where('user_id', $user->id);
            
        if ($status !== null) {
            if ($status == 2) {
                // 已过期
                $query->whereHas('coupon', function ($query) {
                    $query->where('end_time', '<', date('Y-m-d H:i:s'));
                });
            } else {
                $query->where('status', $status)
                    ->whereHas('coupon', function ($query) {
                        $query->where('end_time', '>=', date('Y-m-d H:i:s'));
                    });
            }
        }
        
        $coupons = $query->orderBy('id', 'desc')
            ->paginate($pageSize, ['*'], 'page', $page);
            
        return json(['code' => 0, 'msg' => 'success', 'data' => $coupons]);
    }
    
    /**
     * @Apidoc\Title("检查优惠券是否可用")
     * @Apidoc\Method("POST")
     * @Apidoc\Url("/api/coupon/check")
     * @Apidoc\ParamType("json")
     * @Apidoc\Param("coupon_id", type="int", require=true, desc="优惠券ID")
     * @Apidoc\Param("total_amount", type="number", require=true, desc="订单总金额")
     * @Apidoc\Param("product_ids", type="array", desc="商品ID数组")
     * @Apidoc\Param("category_ids", type="array", desc="分类ID数组")
     */
    public function check(Request $request)
    {
        $user = $request->user;
        $data = $request->post();
        
        try {
            // 获取用户优惠券
            $userCoupon = UserCouponModel::with(['coupon'])
                ->where('user_id', $user->id)
                ->where('coupon_id', $data['coupon_id'])
                ->where('status', 0)
                ->first();
                
            if (!$userCoupon) {
                throw new BusinessException('优惠券不存在或已使用');
            }
            
            $coupon = $userCoupon->coupon;
            
            // 检查有效期
            if ($coupon->end_time < date('Y-m-d H:i:s')) {
                throw new BusinessException('优惠券已过期');
            }
            
            // 检查最低使用金额
            if ($data['total_amount'] < $coupon->min_amount) {
                throw new BusinessException('未达到优惠券使用门槛');
            }
            
            // 检查使用范围
            if ($coupon->use_type > 0) {
                if ($coupon->use_type == 1) {
                    // 指定分类
                    if (empty(array_intersect($data['category_ids'], $coupon->category_ids))) {
                        throw new BusinessException('该优惠券不适用于当前商品');
                    }
                } else if ($coupon->use_type == 2) {
                    // 指定商品
                    if (empty(array_intersect($data['product_ids'], $coupon->product_ids))) {
                        throw new BusinessException('该优惠券不适用于当前商品');
                    }
                }
            }
            
            // 计算优惠金额
            $discountAmount = 0;
            if ($coupon->type == 1) {
                // 满减券
                $discountAmount = $coupon->amount;
            } else if ($coupon->type == 2) {
                // 折扣券
                $discountAmount = $data['total_amount'] * (1 - $coupon->amount / 100);
            }
            
            return json([
                'code' => 0, 
                'msg' => 'success', 
                'data' => [
                    'can_use' => true,
                    'discount_amount' => $discountAmount,
                ]
            ]);
        } catch (\Exception $e) {
            return json([
                'code' => 0,
                'msg' => 'success',
                'data' => [
                    'can_use' => false,
                    'reason' => $e->getMessage(),
                ]
            ]);
        }
    }
} 